<template>
	<view class="bodys">
		<view class="scroll_box" id="scroll_box">
			<scroll-view :style="{ height: scrollHeight + 'px' }" scroll-y='true' class="left_box"
				:scroll-into-view="leftIntoView">
				<view class="left_item" v-for="(item,i) in category_list" :key='i' @click="onLeft" :data-index="i"
					:id="'left-'+i" :class="{select:i == leftIndex}">
					{{item.cate_name}}
				</view>
			</scroll-view>
			<scroll-view :style="{ height: scrollHeight + 'px' }" @scroll="mainScroll" :scroll-into-view="scrollInto"
				scroll-y='true' class="right_box" scroll-with-animation="true">
				<slot></slot>
				<view class="category_img">
					<view class="top_img">
						<image class="recommend_Img" src="../../static/img/category/swiper-banner.png" mode=""></image>
					</view>
					<view class="right_item" v-for="(item,i) in goods_list" :key='i' :id="'item-'+i">
						<view class="caregory_six">
							<u-divider :text="item.cate_name"></u-divider>
						</view>
						<view class="flex-item">
							<view class="img_item" v-for="(items,j) in item.children" :key='j'
								@click="()=>handleNavigateTo(items)">
								<image class="iamge" :src=items.pic mode=""></image>
								<text class="goods_text">{{items.cate_name}}</text>
							</view>
						</view>
					</view>
				</view>

				<view class="fill-last" :style="{ height: fillHeight + 'px' }"></view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import { product } from '@/api'
	export default {
		name: "side-navigation",
		data() {
			return {
				leftArray: [],
				rightArray: [],
				scrollHeight: 400,
				scrollInto: "",
				leftIndex: 0,
				topArr: [],
				scrollTopSize: 0,
				fillHeight: 0, // 填充高度，用于最后一项低于滚动区域时使用
				isActive: 0,
				category_list: [],
				goods_list: [],
			}
		},
		computed: {
			/* 计算左侧滚动位置定位 */
			leftIntoView() {
				return `left-${this.leftIndex > 3 ? this.leftIndex - 3 : 0}`;
			}
		},
		mounted() {
			/* 等待DOM挂载完成 */
			this.$nextTick(() => {
				/* 在非H5平台，nextTick回调后有概率获取到错误的元素高度，则添加200ms的延迟来减少BUG的产生 */
				setTimeout(() => {
					/* 等待滚动区域初始化完成 */
					this.initScrollView().then(() => {
						/* 获取列表数据，你的代码从此处开始 */
						this.getListData();
					});
				}, 200);
			});
			this.initCategory()
		},
		methods: {
			/* 初始化滚动区域 */
			initScrollView() {
				return new Promise((resolve, reject) => {
					let view = uni.createSelectorQuery().select('#scroll_box');
					view.boundingClientRect(res => {
						this.scrollTopSize = res.top;
						this.scrollHeight = res.height;
						this.$nextTick(() => {
							resolve();
						});
					}).exec();
				});
			},
			// 获取数据
			getListData() {
				new Promise((resolve, reject) => {
					uni.showLoading();
					setTimeout(() => {
						let [left, main] = [
							[],
							[]
						];

						for (let i = 0; i < 25; i++) {
							left.push(`${i + 1}类商品`);

							let list = [];
							let r = Math.floor(Math.random() * 10);
							r = r < 1 ? 3 : r;
							for (let j = 0; j < r; j++) {
								list.push(j);
							}
							main.push({
								title: `第${i + 1}类商品标题`,
								list
							});
						}
						// 将请求接口返回的数据传递给 Promise 对象的 then 函数。
						resolve({
							left,
							main
						});
					}, 1000);
				}).then(res => {
					uni.hideLoading();
					this.leftArray = res.left;
					this.rightArray = res.main;
					// DOM 挂载后 再调用 getElementTop 获取高度的方法。
					this.$nextTick(() => {
						this.getElementTop();
					});
				});
			},
			// 获取元素顶部信息
			getElementTop() {
				new Promise((resolve, reject) => {
					let view = uni.createSelectorQuery().selectAll('.right_item');
					view.boundingClientRect(data => {
						resolve(data);
					}).exec();
				}).then(res => {
					let topArr = res.map(item => {
						return item.top - this.scrollTopSize; /* 减去滚动容器距离顶部的距离 */
					});
					this.topArr = topArr;

					/* 获取最后一项的高度，设置填充高度。判断和填充时做了 +-20 的操作，是为了滚动时更好的定位 */
					let last = res[res.length - 1].height;
					if (last - 20 < this.scrollHeight) {
						this.fillHeight = this.scrollHeight - last + 20;
					}
				});
			},
			// 点击左侧导航
			onLeft(e) {
				const index = e.currentTarget.dataset.index;
				// this.leftIndex = index
				this.scrollInto = `item-${index}`
			},
			// 右侧滑动
			mainScroll(e) {
				let top = e.detail.scrollTop;
				let index = 0;
				/* 查找当前滚动距离 */
				for (let i = this.topArr.length - 1; i >= 0; i--) {
					/* 在部分安卓设备上，因手机逻辑分辨率与rpx单位计算不是整数，滚动距离与有误差，增加2px来完善该问题 */
					if (top + 2 >= this.topArr[i]) {
						index = i;
						break;
					}
				}
				this.leftIndex = index < 0 ? 0 : index;
			},
			// 加载分类
			async initCategory() {
				let { status, msg, data } = await product.category();
				if (status === 200) {
					this.category_list = data
					this.goods_list = [...this.category_list]
				}
			},
			// 根据id加载搜索页面
			handleNavigateTo(item) {
				let { id, cate_name } = item;
				uni.setStorageSync("sid", id, );
				uni.setStorageSync("title", cate_name);
				uni.navigateTo({
					url: '/pages/goods_list/goods_list',
				})
			}
		}
	}
</script>

<style>
	page,
	.bodys {
		height: 100%;
	}

	.scroll_box {
		display: flex;
		height: 100%;
	}

	.left_box {
		background-color: #f8f8f8;
		width: 163rpx;
	}

	.left_item {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50rpx;
		width: 163rpx;
		padding: 34rpx 0;
		border-left: 3px solid transparent;
	}

	.select {
		color: #c55a5c;
		font-weight: bold;
		background-color: white;
		border-left: 3px solid #c55a5c;
	}

	.category_content {
		display: flex;
		height: 100%;
		overflow: hidden;
	}

	.category_list {
		display: flex;
		flex-flow: column;
		width: 163rpx;
		border-right: 1px solid #bbb;
		height: 100%;
		overflow: auto;
	}

	.list_item {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50rpx;
		width: 163rpx;
		margin: 34rpx 0;
	}

	.active {
		position: absolute;
		left: 0;
		width: 6rpx;
		height: 50rpx;
		background-color: #c55a5c;
	}

	.category_img {
		width: 532rpx;
		margin: 0 auto;
	}

	.top_img {
		display: flex;
		justify-content: center;
		margin-bottom: 42rpx;
	}

	.recommend_Img {
		width: 528rpx;
		height: 192rpx;
		border-radius: 10rpx;
	}

	.caregory_six {
		color: #555;
		margin-bottom: 58rpx;
		width: 70%;
		margin: 0 auto;
	}

	.list_img {
		display: flex;
		flex-flow: wrap;
	}


	.flex-item {
		display: flex;
		flex-flow: wrap;
	}

	.flex-item .img_item {
		width: 111rpx;
		height: 155rpx;
		display: flex;
		flex-flow: column;
		align-items: center;
		margin: 0 31rpx 0 33rpx;
		margin-bottom: 44rpx;
	}

	.iamge {
		width: 111rpx;
		height: 111rpx;
	}

	.category_text {
		font-size: 26rpx;
		cursor: pointer;
	}

	.goods_text {
		margin-top: 20rpx;
		font-size: 24rpx;
	}

	.goods_title {
		font-size: 26rpx;
	}
</style>